<template>
  <div class="pie_box" ref="echartDom"></div>
</template>

<script setup lang="ts">
/*
传参格式：
写出来的都是必传
可以自己加参数会追加
    legendStyle = {// 图例样式
      show: true,
      icon: "rect",
      left: 0,
      top: 0,
      itemWidth: 0,
      itemHeight: 0,
      itemGap: 0,
    };
    gridConfig = {// 网格样式
    };
     seriesStyle:{//series数据样式
        radius: [15, 50],
        center: ['25%', '55%'],
    },
    seriesData:[//series数据
        [
        { value: 26, name: '实物配租' },
        { value: 5, name: '共有产权房' },
        { value: 20, name: '租金补贴' },
        { value: 5, name: '其他' },
        ]
    ]
*/
import { inject, ref, shallowRef, onMounted, onUnmounted, watch, toRaw, watchEffect, defineEmits } from "vue";

// 接收参数
const props = defineProps({
  housingSupplyStatsData: {
    type: Object,
    default: () => { },
  },
});
// 数据定义
const echartDom = ref<null | HTMLDivElement>(null);
const myChart = shallowRef<null | any>(null);
const echarts = inject<any>("echarts");
const emit = defineEmits(['dialogPieData1'])
// 字体自适应方法
const pxToRem = (px: number) => {
  const scale = document.documentElement.clientWidth / 1920;
  return Math.round(px * Math.min(scale, 3));
};
// echarts初始化渲染
let legendStyle = props.housingSupplyStatsData.legendStyle//图例
let gridStyle = props.housingSupplyStatsData.gridStyle//网格
let seriesData = props.housingSupplyStatsData.seriesData//serires数据
let seriesStyle = props.housingSupplyStatsData.seriesStyle//serires配置

const getEchart = () => {
  if (echartDom.value) {
    myChart.value = echarts.init(echartDom.value);
    // 图例配置
    const legendConfig = {
      show: legendStyle.show,
      icon: legendStyle.icon,
      orient: legendStyle.orient,
      left: pxToRem(legendStyle.left) ? pxToRem(legendStyle.left) : legendStyle.left,
      right: pxToRem(legendStyle.right),
      top: typeof legendStyle.top == "number" ? pxToRem(legendStyle.top) : legendStyle.top,
      bottom: pxToRem(legendStyle.bottom),
      width: pxToRem(5),
      itemWidth: pxToRem(legendStyle.itemWidth),
      itemHeight: pxToRem(legendStyle.itemHeight),
      itemGap: pxToRem(legendStyle.itemGap),
      textStyle: {
        rich: {
          one: {
            width: pxToRem(30),
            height: pxToRem(50),
            color: 'white',
            fontSize: pxToRem(10),
          },
          two: {
            color: 'white',
            fontSize: pxToRem(10),
          }

        },
      },
      formatter: (name) => {
        let value;
        let countAll = 0
        seriesData[0].map((item: any) => {
          if (name == item.name) {
            value = item.value
          }
          countAll += item.value
        })
        const num = 2
        let percent = ((value / countAll) * 100).toFixed(2)
        if (name.length > num) {
          // 如果名称长度超过10，则截取前5个字符和后5个字符，中间使用省略号
          return `{one|${name.substring(0, num)}...}{two|${isNaN(percent) ? 0.00:percent}%}`;
        } else {
          return `{one|${name}}{two|${isNaN(percent) ? 0.00:percent}%}`;
        }
      },

      tooltip: {
        show: true,
        formatter: (res) => {
          let value;
          let countAll = 0
            seriesData[0].map((item: any) => {
              if (res.name == item.name) {
                value = item.value
              }
              countAll += item.value
            })
          if(countAll == 0){
            return `项目名称：${res.name}</br>占比：0%`;
          }else{
            let percent = ((value / countAll) * 100).toFixed(2)
            return `项目名称：${res.name}</br>占比：${percent}%`;
          }
        },

      },

    };
    // 追加项
    for (let j in legendStyle) {
      if (j != 'show' && j != 'icon' && j != 'left' && j != 'right' && j != 'top' && j != 'itemWidth' && j != 'itemHeight' && j != 'itemGap' && j != ' textStyle') {
        legendConfig[j] = toRaw(legendStyle[j])
      }
    }
    // series配置
    let seriesConfig = seriesData.map((item, index) => {
      return {
        name: '',
        type: 'pie',
        center: toRaw(seriesStyle.center),
        radius: [pxToRem(toRaw(seriesStyle.radius)[0]), pxToRem(toRaw(seriesStyle.radius)[1])],
        itemStyle: {
          borderRadius: pxToRem(2),
          backgroundColor: 'red'
        },
        data: toRaw(seriesData[index])
      }
    })
    // 追加项
    for (let i in seriesStyle) {
      if (i != 'radius' && i != 'center' && i != ' type' && i != ' seriesData') {
        seriesConfig[0][i] = toRaw(seriesStyle[i])
      }
    }
    //绘图
    const option = {
      tooltip: {
        trigger: "item",
        axisPointer: {
          type: "line",
          lineStyle: {
            color: "rgba(40,252,255,0.6)",
            shadowBlur: 10,
            shadowColor: "rgba(0, 0, 0, 0.9)",
          },
        },
        position: function (point, params, dom, rect, size) {
          return [point[0], '5%']; // 示例：将 tooltip 定位在鼠标的水平位置和视窗顶部 10% 的位置
        },
        textStyle: {
          color: "#fff",
          fontSize: pxToRem(18),
        },
        backgroundColor: "rgba(47, 99, 205, 0.5)",
        borderColor: '#66FFFF', // 设置边框颜色为红色
        borderWidth: 1, // 设置边框宽度
      },
      legend: legendConfig,
      series: seriesConfig
    }
    myChart.value.setOption(option);
    myChart.value.on("click", (params) => {
      emit('dialogPieData1', props.housingSupplyStatsData)
    });
  }
};
const updateChart = () => {
  if (myChart.value) {
    myChart.value.dispose(); // 销毁旧图表实例
  }
  legendStyle = props.housingSupplyStatsData.legendStyle//图例
  gridStyle = props.housingSupplyStatsData.gridStyle//网格
  seriesData = props.housingSupplyStatsData.seriesData//serires数据
  seriesStyle = props.housingSupplyStatsData.seriesStyle//serires配置 
  getEchart();
};

watchEffect(() => {
  updateChart();
});

onMounted(() => {
  getEchart();
  window.addEventListener("resize", () => {
    if (myChart.value) {
      myChart.value.dispose(); // 销毁旧图表实例
    }
    getEchart(); // 创建新的图表实例
  });
});

onUnmounted(() => {
  window.removeEventListener("resize", () => {
    if (myChart.value) {
      myChart.value.dispose(); // 在组件销毁时也需要销毁图表实例
    }
  });
});
</script>

<style scoped lang="less">
.pie_box {
  width: 100%;
  height: 100%;
}

.echarts-background {
  background-color: transparent !important;
}
</style>
